package com.webside.front.homepage.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.webside.front.advertisement.controller.advertisementController;
import com.webside.front.common.model.BSeries;
import com.webside.front.common.model.Bdictionary;
import com.webside.front.common.model.PBanner;
import com.webside.front.common.model.SubjectEntity;
import com.webside.front.common.model.VideoFromWeb;
import com.webside.front.common.service.BAdPositionService;
import com.webside.front.common.service.BSeriesService;
import com.webside.front.common.service.BdictionaryService;
import com.webside.front.common.service.PBannerService;
import com.webside.front.index.service.IndexService;
import com.webside.front.listener.BaseData;
import com.webside.front.search.service.SearchService;
import com.webside.mongo.model.AdRecord;
import com.webside.util.Common;
import com.webside.util.HttpUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@Controller
@SessionAttributes(types = PBanner.class)
@RequestMapping(value = "/common/")
public class HomeController {
	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private BdictionaryService bdictionaryService;
	@Autowired
	private BSeriesService bSeriesService;
	@Autowired
	private BAdPositionService bAdPositionService;
	@Autowired
	private IndexService indexService;
	@Autowired
	private PBannerService pBannerService;
	private Configuration freemarker_cfg = null;

	/**
	 * 查询轮播海报和视频
	 * 
	 * @param m
	 * @return
	 */
	@RequestMapping("index.html")
	public String selectAll(Model m, Bdictionary bdictionary, HttpServletRequest request) {
		if (false) {
			this.staticCreat(request.getContextPath(),request);
		}
		return Common.BACKGROUND_PATH + "/front/index1";

	}
	
	@RequestMapping(method = RequestMethod.POST, value ="addAdRecord.html")
	public @ResponseBody void addAdRecord(AdRecord adRecord, HttpServletRequest request) {
		System.out.println("进到首页了吗————————————");
		adRecord.setBrowerTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
		adRecord.setBrowerDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		// 调用java自带的uuid生成唯一标示id
		UUID uuid = UUID.randomUUID();
		// 去掉不需要的字符
		String id = uuid.toString().replaceAll("\\-", "");
		// 为实体对象加入标示id
		adRecord.setId(id);
		adRecord.setSessionId(request.getSession().getId());
		System.out.println(adRecord.getIp());
		adRecord.setProvince(HttpUtil.getProvince(adRecord.getIp()));
		adRecord.setCity(HttpUtil.getCity(adRecord.getIp()));
		mongoTemplate.insert(adRecord, "ad_brower_records");
	}
	@RequestMapping("show.html")
	public String showHome(HttpServletRequest req,HttpServletResponse res,Model model){
		/*
		 * 图片根路径
		 */
		model.addAttribute("baseImgPath",BaseData.img_base_path);
		/*
		 * 搜索关键字 
		 */
		model.addAttribute("keyWords",this.getSearchKeyWords());
		// 查询轮播图
		Map<String, Object> banner = new HashMap<String,Object>();
		banner.put("target", "BANNER");
		banner.put("orderColumn", "sort");
		banner.put("orderType", "ASC");
		banner.put("pageSize", 5);
		banner.put("channel","INDEX");
		List<PBanner> bannerlist = pBannerService.selectBannerByCondition(banner);
		model.addAttribute("banner_list", bannerlist);
		//热点
		Map<String,Object> condition = new HashMap<>();
		List<VideoFromWeb> BigRedianSeriesList = indexService.selectReDianPlayFirst(condition);
		if(BigRedianSeriesList.size()>0){
			model.addAttribute("redian_first", BigRedianSeriesList.get(0));
		}else{
			model.addAttribute("redian_first", null);
		}
		List<VideoFromWeb> redianSeriesList = indexService.selectReDianPlay(condition);
		model.addAttribute("redian_list", redianSeriesList);
		//专题
		List<SubjectEntity> subjectList = indexService.getSubjectList();
		model.addAttribute("sub_list", subjectList);
		//热剧天天看
		List<BSeries> tvSeriesList = indexService.selectTVPlay(condition);
		model.addAttribute("play_list", tvSeriesList);
		// 电视剧风云榜内地港台日韩10*3
		List<BSeries> guoNeiTvSeriesList = indexService.selectGuoNeiTVPlay(condition);//国内
		List<BSeries> riHanTvSeriesList = indexService.selectRiHanTVPlay(condition);//日韩
		List<BSeries> ouMeiTvSeriesList = indexService.selectOuMeiTVPlay(condition);//欧美
		model.addAttribute("guoneiTV_list", guoNeiTvSeriesList);
		model.addAttribute("rihanTV_list", riHanTvSeriesList);
		model.addAttribute("oumeiTV_list", ouMeiTvSeriesList);
		//精彩花絮6
		List<VideoFromWeb> huaxuSeriesList = indexService.selectHuaXuPlay(condition);
		model.addAttribute("huaxu_list", huaxuSeriesList);
		//佳片有约10
		List<BSeries> jiaPianSeriesList = indexService.selectMoviePlay(condition);
		model.addAttribute("jiapian_list", jiaPianSeriesList);
		//佳片风云榜10*3
		List<BSeries> guoNeiMovieSeriesList = indexService.selectGuoNeiMoviePlay(condition);//国内
		List<BSeries> riHanMovieSeriesList = indexService.selectRiHanMoviePlay(condition);//日韩
		List<BSeries> ouMeiMovieSeriesList = indexService.selectOuMeiMoviePlay(condition);//欧美
		model.addAttribute("guoneiMovie_list", guoNeiMovieSeriesList);
		model.addAttribute("rihanMovie_list", riHanMovieSeriesList);
		model.addAttribute("oumeiMovie_list", ouMeiMovieSeriesList);
		
		//广告位 通栏 1 2 3
		model.addAttribute("bannerOne", bAdPositionService.selectPositionByCode("BANNERONE"));
		model.addAttribute("bannerTwo",bAdPositionService.selectPositionByCode("BANNERTWO"));
		model.addAttribute("bannerThree",bAdPositionService.selectPositionByCode("BANNERTHREE"));
		//广告位 方形1 2
		model.addAttribute("rectOne", bAdPositionService.selectPositionByCode("RECTONE"));
		model.addAttribute("rectTwo", bAdPositionService.selectPositionByCode("RECTTWO"));
		
		
		//预告片花6
		List<VideoFromWeb> yuGaoSeriesList = indexService.selectYuGaoPlay(condition);
		model.addAttribute("yugao_list", yuGaoSeriesList);
		//综艺1大6小
		List<BSeries> BigVaritySeriesList = indexService.selectVarityPlayFirst(condition);
		if(BigVaritySeriesList.size()>0){
			model.addAttribute("varity_first", BigVaritySeriesList.get(0));
		}else{
			model.addAttribute("varity_first", null);
		}
		
		List<BSeries> varitySeriesList = indexService.selectVarityPlay(condition);
		model.addAttribute("varity_list", varitySeriesList);
		//综艺风云榜6
		List<BSeries> varityBangSeriesList = indexService.selectVarityPlayBang(condition);
		model.addAttribute("varityBang_list", varityBangSeriesList);
		//娱乐八卦6
		List<VideoFromWeb> yuLeSeriesList = indexService.selectYuLePlay(condition);
		model.addAttribute("yule_list", yuLeSeriesList);
		//动漫1大6小
		List<BSeries> BigCartoonSeriesList = indexService.selectCartoonPlayFirst(condition);
		if(BigCartoonSeriesList.size()>0){
			model.addAttribute("cartoon_first", BigCartoonSeriesList.get(0));
		}else{
			model.addAttribute("cartoon_first", null);
		}
		
		List<BSeries> CartoonSeriesList = indexService.selectCartoonPlay(condition);
		model.addAttribute("cartoon_list", CartoonSeriesList);
		//动漫风云榜6
		List<BSeries> CartoonBangSeriesList = indexService.selectCartoonBangPlay(condition);
		model.addAttribute("cartoonBang_list", CartoonBangSeriesList);
		
		
		// 查询合作伙伴
		List<PBanner> Targets = indexService.getAllTarget();
		model.addAttribute("target_list", Targets);
		return Common.BACKGROUND_PATH + "/front/homePage/homePage";
		
	}
	
	/**
	 * 获取搜寻关键字
	 */
	private List<String> getSearchKeyWords(){
		Map<String, Object> keyWords = new HashMap<String, Object>();
		keyWords.put("type", "SEARCH_KEYWORDS");
		keyWords.put("code","SEARCH_KEYWORDS");
		List<Bdictionary> list = bdictionaryService.selectBdictionaryByCondition(keyWords);
		List<String> keyWord = new ArrayList<String>();
		String[] str = new String[]{};
		for (Bdictionary b : list) {
			str = b.getName().split(",");
			List<String> l = Arrays.asList(str);
			keyWord.addAll(l);
		}
		return keyWord;
	}
	/**
	 * 创建多级目录
	 * 
	 * @param path
	 *            String
	 * @return boolean 是否成功
	 */
	private boolean creatDirs(String path) {
		File aFile = new File(path);
		if (!aFile.exists()) {
			return aFile.mkdirs();
		} else {
			return true;
		}
	}

	/**
	 * 
	 * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取.
	 * 
	 * @param templateFilePath
	 *            获取模板路径
	 * @return Configuration 返回freemaker的配置属性
	 * @throws Exception
	 */
	private Configuration getFreeMarkerCFG(String templateFilePath) throws Exception {
		if (null == this.freemarker_cfg) {

			this.freemarker_cfg = new Configuration();
			try {
				this.freemarker_cfg.setDirectoryForTemplateLoading(new File(templateFilePath));
			} catch (Exception ex) {
				throw ex;
			}
		}
		return this.freemarker_cfg;
	}

	/**
	 * 生成静态文件.
	 * 
	 * @param templateFileName
	 *            模板文件名,相对htmlskin路径,例如"/tpxw/view.ftl"
	 * @param propMap
	 *            用于处理模板的属性Object映射
	 * @param htmlFilePath
	 *            要生成的静态文件的路径,相对设置中的根路径,例如 "/tpxw/1/2005/4/"
	 * @param htmlFileName
	 *            要生成的文件名,例如 "1.htm"
	 * @param templateFilePath
	 *            模板路径
	 * @return boolean true代表生成文件成功
	 */
	public void geneHtmlFile(String templateFileName, Map propMap, String htmlFilePath, String htmlFileName,
			String templateFilePath) {

		try {
			Template t = this.getFreeMarkerCFG(templateFilePath).getTemplate(templateFileName);
			// 如果根路径存在,则递归创建子目录
			this.creatDirs(htmlFilePath);
			File afile = new File(htmlFilePath + "/" + htmlFileName);
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(afile), "UTF-8"));
			t.process(propMap, out);
			out.flush();
			out.close();
		} catch (TemplateException e) {
			System.out.print(e.getMessage());
		} catch (IOException e) {
			System.out.print(e.getMessage());
		} catch (Exception e) {
			System.out.print(e.getMessage());
		}
	}
	
	@RequestMapping("createIndexHtml.html")
	public String createIndexHtml(Model m, Bdictionary bdictionary, HttpServletRequest request) {
		this.staticCreat(request.getContextPath(),request);
		
		return Common.BACKGROUND_PATH + "/front/test";
	}

	public void staticCreat(String basepath,HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		BSeries record = new BSeries();
		Bdictionary dbict = new Bdictionary();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String date = format.format(new Date());
		VideoFromWeb videoFromWeb=new VideoFromWeb();
		/*
		 * Map ReleaseAd=new HashMap<String,String>();
		 * ReleaseAd.put("resource_url", null); ReleaseAd.put("link_url", null);
		 * ReleaseAd.put("ad_interval", null); ReleaseAd.put("status", null);
		 */
		// 广告投放
		List<HashMap<String, Object>> BANNER1 = indexService.queryAdByAll(date, "BANNERONE");
		List<HashMap<String, Object>> BANNER2 = indexService.queryAdByAll(date, "BANNERTWO");
		List<HashMap<String, Object>> BANNER3 = indexService.queryAdByAll(date, "BANNERTHREE");
		List<HashMap<String, Object>> BANNER4 = indexService.queryAdByAll(date, "BANNERFOUR");
		List<HashMap<String, Object>> RECT1 = indexService.queryAdByAll(date, "RECTONE");
		List<HashMap<String, Object>> RECT2 = indexService.queryAdByAll(date, "RECTTWO");
		List<HashMap<String, Object>> RECT3 = indexService.queryAdByAll(date, "RECTTHREE");
		map=this.releaseBannerAd(BANNER1, map,"banner1_list","banner1");
		map=this.releaseBannerAd(BANNER2, map,"banner2_list","banner2");
		map=this.releaseBannerAd(BANNER3, map,"banner3_list","banner3");
		map=this.releaseBannerAd(BANNER4, map,"banner4_list","banner4");
		map=this.releaseRectAd(RECT1, map,"rect1_list","rect1");
		map=this.releaseRectAd(RECT2, map,"rect2_list","rect2");
		map=this.releaseRectAd(RECT3, map,"rect3_list","rect3");
		
		// 查询关键词
		List<Bdictionary> keywords = indexService.selectKeywords();
		String[] keyarr = keywords.get(0).getName().split(",");
		map.put("bdictionaryKeywords_list", keyarr);
		// 查询关键词
		List<Bdictionary> pageInfo = indexService.selectPageInfo();
		map.put("bdictionaryPageInfo", pageInfo);
		// 查询电影的类型
		List<Bdictionary> ByPrimary = indexService.selectByPrimary(dbict);
		map.put("bdictionaryByPrimary_list", ByPrimary);
		// 查询电视剧的类型
		List<Bdictionary> TVplay = indexService.selectTVplay(dbict);
		map.put("bdictionaryTVplay_list", TVplay);
		// 查询动漫的类型
		List<Bdictionary> Comic = indexService.selectComic(dbict);
		map.put("bdictionaryComic_list", Comic);
		// 猜你喜欢
		List<BSeries> xihun = indexService.selectByPrimarySelective(record);
		map.put("xihun_list", xihun);
		// 激情预告
		
		List<VideoFromWeb> Trailer1 = indexService.selectTrailer();
		map.put("Trailer1", Trailer1.get(0));
		map.put("Trailer_list", Trailer1);
		// 卫视同步
		List<BSeries> Satellite = indexService.selectByallSatellite(record);
		map.put("Satellite_list", Satellite);
		List<BSeries> Satellite1 = indexService.selectSatellite(record);
		map.put("Satellite1_list", Satellite1);
		// 日韩热播
		List<BSeries> Korea = indexService.selectByKorea(record);
		map.put("Korea_list", Korea);
		List<BSeries> Korea1 = indexService.selectKorea(record);
		map.put("Korea1_list", Korea1);
		// 美剧精选
		List<BSeries> American = indexService.selectAmerican(record);
		map.put("American_list", American);
		// 佳品有约
		List<BSeries> Jiapin = indexService.selectJiapin(record);
		map.put("Jiapin_list", Jiapin);
		List<BSeries> ByJiapin = indexService.selectByJiapin(record);
		map.put("ByJiapin_list", ByJiapin);
		List<BSeries> ByALLJiapin = indexService.selectByALLJiapin(record);
		map.put("ByALLJiapin_list", ByALLJiapin);
		// 影院大片
		List<BSeries> Cinema = indexService.selectCinema(record);
		map.put("Cinema_list", Cinema);
		// 动漫剧场
		List<BSeries> Animation = indexService.selectByAnimation(record);
		map.put("Animation_list", Animation);
		List<BSeries> Mation = indexService.selectAnimation(record);
		map.put("Mation_list", Mation);
		// 电视剧榜
		List<BSeries> play = indexService.selectplay(record);
		map.put("play_list", play);
		// 电视剧影迷力荐
		List<BSeries> ByTvplay = indexService.selectByTvplayALL();
		map.put("ByTvplay_list", ByTvplay);
		// 佳品电影榜
		List<BSeries> Jiapinplay = indexService.selectJiapinplay(record);
		map.put("Jiapinplay_list", Jiapinplay);
		// 佳品电影影迷力荐
		List<BSeries> LikeCounts = indexService.selectByLikeCount();
		map.put("LikeCount_list", LikeCounts);

		// 影迷力荐
		List<BSeries> BSeries = indexService.selectByPrimaryALL();
		map.put("BSeries_list", BSeries);
		// 查询轮播图
		List<PBanner> list = indexService.getAllSubject();
		map.put("banner_list", list);
		// 查询轮播图广告
		List<HashMap<String, Object>> FOCUS = indexService.queryAdByAll(date, "FOCUSONE");
		if (FOCUS.size() > 0) {
			for (int i = 0; i < FOCUS.size(); i++) {
				PBanner pBanner = new PBanner();
				list.add(pBanner);
				list.get(list.size() - 1).setImgUrl(FOCUS.get(i).get("resource_url").toString());
				list.get(list.size() - 1).setLinkUrl(FOCUS.get(i).get("link_url").toString());
				list.get(list.size() - 1)
						.setTarget("count='0' pcode='" + FOCUS.get(i).get("code") + "' pname='"
								+ FOCUS.get(i).get("name") + "' adid='" + FOCUS.get(i).get("id") + "' adtitle='"
								+ FOCUS.get(i).get("title") + "' adtypename='" + FOCUS.get(i).get("type_name")
								+ "' adtype='" + FOCUS.get(i).get("type") + "' onclick='wordsinsert(this)'");

			}
		}
		// 查询合作伙伴
		List<PBanner> Targets = indexService.getAllTarget();
		map.put("Target_list", Targets);
		map.put("baseImgPath", BaseData.img_base_path);
		map.put("basePath", basepath);
		map.put("Navigation", "导航");
		map.put("regi", "注册");
		map.put("loggin", "登录");
		map.put("Movie", "电影");
		map.put("TV", "电视剧");
		map.put("Comic", "动漫");
		map.put("Recommend", "影迷力荐");
		map.put("like", "猜你喜欢");
		map.put("Trailer", "激情预告");
		map.put("synchronization", "卫视同步");
		map.put("top", "电视剧榜");
		map.put("movief", "影友推荐");
		map.put("kjrb", "日韩热播");
		map.put("mjjx", "美剧精选");
		map.put("jpyy", "佳片有约");
		map.put("db", "独播");
		map.put("dyb", "电影榜");
		map.put("yxdp", "院线大片");
		map.put("dmjc", "动漫剧场");
		map.put("hzhb", "合作伙伴");
		map.put("copyright", "沪ICP备15015296号-4 | Copyright © 2016 All Rights Reserved.");

		this.geneHtmlFile("index.ftl", map, request.getSession().getServletContext().getRealPath("/WEB-INF/view/front/"), "index.html",
				request.getSession().getServletContext().getRealPath("/WEB-INF/ftl/"));
		System.out.println(request.getSession().getServletContext().getRealPath("/WEB-INF/view/f/")+"===============");
	}
	public Map<String, Object> releaseRectAd(List<HashMap<String, Object>> list,Map<String, Object> map,String AdPos,String AdPos2){
		if (list.size() > 0) {
			List<String> lists = new ArrayList<String>();
			String AdRelease = "";
			for (int i = 0; i < list.size(); i++) {

				AdRelease = "<a target='target' class='"+AdPos2+"' status='" + list.get(i).get("status") + "' interval='"
						+ list.get(i).get("ad_interval") + "' href='" + list.get(i).get("link_url")
						+ "'><img count='0' pcode='" + list.get(i).get("code") + "' pname='" + list.get(i).get("name")
						+ "' adid='" + list.get(i).get("id") + "' adtitle='" + list.get(i).get("title")
						+ "' adtypename='" + list.get(i).get("type_name") + "' adtype='" + list.get(i).get("type")
						+ "' onclick='wordsinsert(this)' width='228' height='95' src='"
						+ list.get(i).get("resource_url") + "'/></a>";
				lists.add(AdRelease);
			}
			map.put(AdPos, lists);
		}
		return map;
	}
	public Map<String, Object> releaseBannerAd(List<HashMap<String, Object>> list,Map<String, Object> map,String AdPos,String AdPos2){
		if (list.size() > 0) {
			List<String> lists = new ArrayList<String>();
			String AdRelease = "";
			for (int i = 0; i < list.size(); i++) {

				AdRelease = "<a target='target' class='"+AdPos2+"' status='" + list.get(i).get("status") + "' interval='"
						+ list.get(i).get("ad_interval") + "' href='" + list.get(i).get("link_url")
						+ "'><img count='0' pcode='" + list.get(i).get("code") + "' pname='"
						+ list.get(i).get("name") + "' adid='" + list.get(i).get("id") + "' adtitle='"
						+ list.get(i).get("title") + "' adtypename='" + list.get(i).get("type_name")
						+ "' adtype='" + list.get(i).get("type")
						+ "' onclick='wordsinsert(this)' width='1200' height='100' src='"
						+ list.get(i).get("resource_url") + "'/></a>";
				lists.add(AdRelease);
			}
			map.put(AdPos, lists);
		}
		return map;
	}
	public static void main(String[] args) {
		System.out.println("java_vendor:" + System.getProperty("java.vendor"));
		System.out.println("java_vendor_url:" + System.getProperty("java.vendor.url"));
		System.out.println("java_home:" + System.getProperty("java.home"));
		System.out.println("java_class_version:" + System.getProperty("java.class.version"));
		System.out.println("java_class_path:" + System.getProperty("java.class.path"));
		System.out.println("os_name:" + System.getProperty("os.name"));
		System.out.println("os_arch:" + System.getProperty("os.arch"));
		System.out.println("os_version:" + System.getProperty("os.version"));
		System.out.println("user_name:" + System.getProperty("user.name"));
		System.out.println("user_home:" + System.getProperty("user.home"));
		System.out.println("user_dir:" + System.getProperty("user.dir"));
		System.out.println("java_vm_specification_version:" + System.getProperty("java.vm.specification.version"));
		System.out.println("java_vm_specification_vendor:" + System.getProperty("java.vm.specification.vendor"));
		System.out.println("java_vm_specification_name:" + System.getProperty("java.vm.specification.name"));
		System.out.println("java_vm_version:" + System.getProperty("java.vm.version"));
		System.out.println("java_vm_vendor:" + System.getProperty("java.vm.vendor"));
		System.out.println("java_vm_name:" + System.getProperty("java.vm.name"));
		System.out.println("java_ext_dirs:" + System.getProperty("java.ext.dirs"));
		System.out.println("file_separator:" + System.getProperty("file.separator"));
		System.out.println("path_separator:" + System.getProperty("path.separator"));
		System.out.println("line_separator:" + System.getProperty("line.separator"));
	}
}